import React, { Component } from 'react';
import axios from 'axios';
import cookie from 'react-cookies';
import MenuHead from '../comm/menuHead';
import {rsaEncode} from '../comm/rsa';

const personMainTab = "personMainTab";
const personPwdTab = "personPwdTab";
const block = "block";
const none = "none";

class Personal extends Component {
  state = {
    cur_tab: personMainTab,
    pwd: "",
    pub_key: "",
  }
  alter_pwd = () => {
    this.setState({
      cur_tab: personPwdTab,
    })
    this.getPubKey();
  }
  set_pwd = (e) => {
    this.setState({
      pwd: e.target.value,
    })
  }
  clear_pwd = () => {
    this.setState({
      pwd: "",
      cur_tab: personMainTab,
    })
  }
  cancel_alter_pwd = () => {
    this.clear_pwd();
  }
  confirm_alter_pwd = () => {
    this.alterPwd();
    this.clear_pwd();
  }
  getPubKey = () => {
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    axios.post("/app/getPubKey", {
      "userName": userName,
      "loginID": loginID,
    }).then((res) => {
      this.setState({
        pub_key: res.data.pubKey,
      })
    }).catch((err) => {
      alert(err)
    })
  }
  alterPwd = () => {
    let userName = cookie.load('login-name');
    let loginID = cookie.load('login-id');
    if(this.state.pwd === "") {
      alert("请输入密码");
      return;
    }
    if(this.state.pub_key === "") {
      alert("pub_key为空");
      return;
    }
    let pwd = rsaEncode(this.state.pwd, this.state.pub_key);
    console.log(this.state.pwd)
    console.log(this.state.pub_key)
    console.log(pwd)
    axios.post("/app/alterPwd", {
      "user_pwd": pwd,
      "userName": userName,
      "loginID": loginID,
    }).then((res) => {
      if(res.data.error === "") {
        alert("修改成功");
      } else {
        alert("修改失败");
      }
    }).catch((err) => {
      alert(err)
    })
  }
  render() {
    let isPersonMainShow = this.state.cur_tab === personMainTab ? block : none;
    let isPersonPwdShow = this.state.cur_tab === personPwdTab ? block : none;
    return (
      <div align='center'>
        <MenuHead />
        <div style={{display: `${isPersonMainShow}`}}>
          <button onClick={this.alter_pwd}>修改密码</button>
        </div>
        <div style={{display: `${isPersonPwdShow}`}}>
          <br/>
          <table>
          <tbody>
          <tr>
            <td>密码：</td>
            <td><input type='text' size='20' onChange={this.set_pwd}
                  value={this.state.pwd}/></td>
          </tr>
          </tbody>
          </table>
          <br/>
          <table>
          <tbody>
          <tr>
            <td><button onClick={this.cancel_alter_pwd}>取消</button></td>
            <td><button onClick={this.confirm_alter_pwd}>确定</button></td>
          </tr>
          </tbody>
          </table>
        </div>
      </div>
    )
  }
}

export default Personal;
